<script setup lang="ts">
import HomeContent from '@/components/HomeContent/index.vue'
import CommentContent from '@/pages/meeting/components/CommentContent/index.vue'
import { getRoomChatByTimeAPI } from '@/services/room/room'
import { Chats } from '@/services/room/type'
import {
  getHistoryByTypeAPI,
  deleteHistoryAPI
} from '@/services/history/history'
import { useUserStore } from '@/stores'
import { ref } from 'vue'
import { onMounted } from 'vue'
import { HistoryItem, HistoryResponseData } from '@/services/history/type'
import { ElTable as ELTABLE } from 'element-plus'
// 使用用户状态管理
const userStore = useUserStore()

const { getHistoryType } = defineProps<{
  getHistoryType: string
}>()

// 获取历史数据并进行格式转换的函数
const getHistoryByTypeData = async () => {
  // 调用API获取历史数据
  const res: HistoryResponseData = await getHistoryByTypeAPI(
    userStore.userInfo.userInfo.roomId,
    getHistoryType
  )
  // 将历史数据中的时间戳转换为本地时间字符串
  let convertedHistoryList = res.data.historyList.map((item: HistoryItem) => {
    let newItem = { ...item } // 创建一个新对象，避免修改原始数据
    newItem.startTime = new Date(item.startTime).toLocaleString('zh-CN')
    newItem.nearTime = new Date(item.nearTime).toLocaleString('zh-CN')
    newItem.endTime = new Date(item.endTime).toLocaleString('zh-CN')
    return newItem
  })
  // 更新响应式变量historyData的值
  historyData.value = convertedHistoryList
}

// 组件挂载时调用的钩子函数
onMounted(async () => {
  // 获取用户信息
  // await userStore.getUserInfo()
  // 获取历史数据
  getHistoryByTypeData()
})

// 历史数据的响应式引用
const historyData = ref()

// 将要删除的历史项的响应式引用
const toBeDeleted = ref()
// 已选历史项的响应式引用
const deleteList = ref<HistoryItem[]>([])

// 处理删除历史项的函数
const handleDelete = async (row: HistoryItem | boolean) => {
  // 获取当前选中的历史项
  deleteList.value = historyTable.value?.getSelectionRows()
  // 检查是否有选中的历史项
  if (deleteList.value.length === 0 && row === false) {
    // 如果没有，则显示警告信息
    ElMessage.warning('请选择要删除的对象')
  }
  // 设置将要删除的项
  toBeDeleted.value = row
  // 显示对话框
  dialogVisible.value = true
}

// 确认删除操作的函数
const confirmDelete = async () => {
  // 关闭对话框
  dialogVisible.value = false
  if (toBeDeleted.value === false) {
    // 如果为批量删除，则调用deleteHistoryData删除选中的项
    await deleteHistoryData(deleteList.value.map(item => item.id))
  } else {
    // 如果为单个删除，则只删除指定的项
    await deleteHistoryData([(toBeDeleted.value as HistoryItem).id])
  }
  // 显示删除成功的消息
  ElMessage.success('删除成功')
  // 重新获取历史数据
  getHistoryByTypeData()
}

// 发起删除历史数据的API调用的函数
const deleteHistoryData = async (id: number[]) => {
  // 调用API进行删除
  await deleteHistoryAPI({
    roomId: userStore.userInfo.userInfo.roomId,
    id: id
  })
}

// 表格组件的引用
const historyTable = ref<InstanceType<typeof ELTABLE>>()

// 清空选中项的函数
const clearSelection = () => {
  // 清空表格的选中项
  historyTable.value?.clearSelection()
}

const chatList = ref<Chats>()

// 控制对话框显示的响应式变量
const dialogVisible = ref(false)

// 抽屉显示
const drawerFlag = ref(false)
// 抽屉数据
const drawerData = ref<HistoryItem>()
// 抽屉函数
const handleDrawer = async (row: HistoryItem) => {
  drawerData.value = row
  // 发送请求聊天记录的请求
  const res = await getRoomChatByTimeAPI({
    roomId: drawerData.value?.roomId,
    startTime: drawerData.value?.startTime,
    endTime: drawerData.value?.endTime
  })
  chatList.value = res.data.chats
  drawerFlag.value = true
}
</script>
<template>
  <el-dialog v-model="dialogVisible" title="温馨提示" width="30%">
    <span> 你确定要删除嘛 </span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
  <HomeContent>
    <template #title> <slot name="HisType"></slot> </template>
    <template #content>
      <el-table
        ref="historyTable"
        style="width: 100%; height: 100%"
        :data="historyData"
        stripe
        :border="true"
        max-height="600"
        table-layout="auto"
        :header-cell-style="{ background: '#f4f6f8', color: '#000000' }"
        :sortable="true"
      >
        <el-table-column type="selection" />
        <el-table-column label="房间号" prop="roomId"></el-table-column>
        <el-table-column
          label="标题"
          prop="title"
          show-overflow-tooltip
        ></el-table-column>

        <el-table-column
          label="开始时间"
          prop="startTime"
          width="200"
          sortable
        ></el-table-column>
        <el-table-column
          label="最近入会时间"
          prop="nearTime"
          width="200"
        ></el-table-column>
        <el-table-column
          label="结束时间"
          prop="endTime"
          width="200"
          sortable
        ></el-table-column>
        <el-table-column
          label="参会时长"
          prop="continuousTime"
          sortable
        ></el-table-column>
        <el-table-column label="房主" prop="host"></el-table-column>
        <el-table-column label="操作" fixed="right" width="150">
          <template #default="scope">
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
            <el-button
              size="small"
              type="primary"
              @click="handleDrawer(scope.row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div style="margin: 20px 0">
        <el-button type="primary" @click="clearSelection">清空所选</el-button>
        <el-button @click="handleDelete(false)">删除所选</el-button>
      </div>
    </template>
  </HomeContent>
  <el-drawer
    ref="drawerRef"
    v-model="drawerFlag"
    title="历史记录详情"
    class="demo-drawer"
  >
    <div class="demo-drawer__content">
      <el-descriptions direction="horizontal" :column="1" border>
        <el-descriptions-item label="房间号">{{
          drawerData?.roomId
        }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{
          drawerData?.title
        }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">
          {{ drawerData?.startTime }}
        </el-descriptions-item>
        <el-descriptions-item label="结束时间"
          >{{ drawerData?.endTime }}
        </el-descriptions-item>
        <el-descriptions-item label="最近入会时间"
          >{{ drawerData?.nearTime }}
        </el-descriptions-item>
        <el-descriptions-item label="参会时长"
          >{{ drawerData?.continuousTime }}
        </el-descriptions-item>
        <el-descriptions-item label="房主"
          >{{ drawerData?.host }}
        </el-descriptions-item>
        <el-descriptions-item label="聊天记录">
          <CommentContent
            :chatList="(chatList as Chats)"
            :account="userStore.userInfo.userInfo.username"
          ></CommentContent
        ></el-descriptions-item>
      </el-descriptions>
    </div>
  </el-drawer>
</template>

<style scoped lang="less">
:deep(.HomeContainer .meeting_box) {
  justify-content: flex-start !important;
}
</style>
